<template>
  <a-cascader
    v-model='data'
    :options="dataList"
    :load-data="loadData"
    placeholder="请选择"
    :field-names="{ label: 'areaName', value: 'areaName', children: 'children' }"
    change-on-select
    @change="onChange"
  />
</template>
<script>
import { selectArea } from '@/api/public'
import handle from 'ant-design-vue/lib/vc-slider/src/Handle'
export default {
  props: {
    value: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      data: this.value,
      dataList: [],
    };
  },
  created() {
    this.getRegionList(0)
  },
  watch: {
    value: {
      handler(newVal) {
        this.data = newVal
        if (newVal.length == 3) {
          this.getRegionList(0, () => {
            for (let i = 0; i < this.dataList.length; i++) {
              if (this.dataList[i].areaName == newVal[0]) {
                this.getRegionList(this.dataList[i].id, (list) => {
                  this.dataList[i].children = list
                  for (let n = 0; n < list.length; n++) {
                    if (list[n].areaName == newVal[1]) {
                      this.getRegionList(list[n].id, (list) => {
                        this.dataList[i].children[n].children = list
                        this.$forceUpdate()
                      })
                    }
                  }
                })
              }
            }
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 获取地区
    getRegionList(parentId, callBack) {
      selectArea({
        parentId,
      }).then((res) => {
        const list = res.result
        for (let i = 0; i < list.length; i++) {
          if (list[i].areaLevel != 3) {
            list[i].isLeaf = false
          }
        }
        if (parentId == 0) {
          this.dataList = list
        }
        if (callBack) {
          callBack(list)
        }
      })
    },
    onChange(value) {
      this.$emit('input', value)
    },
    loadData(selectedOptions) {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      this.getRegionList(targetOption.id, (list) => {
        targetOption.loading = false;
        targetOption.children = list
        this.dataList = [...this.dataList];
      })
    },
  },
};
</script>